﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void ShowMessage(string msgStr)
        {
            txtLog.AppendText(msgStr + "\r\n");
        }

        private Socket socketSend; 
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                //创建通信对象
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(txtServer.Text);
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));

                //获取连接的远程服务器应用程序的IP地址和端口号
                socketSend.Connect(point);
                ShowMessage("连接" + ip + ":" + txtPort.Text.Trim() + "成功！");

                //开启新线程不停接受服务端发送过来的消息
                Thread th = new Thread(Receive);
                th.IsBackground = true;
                th.Start();
            }
            catch
            {
                MessageBox.Show("网络连接错误，请重新连入！");
            }
        }
        /// <summary>
        /// 给服务端发送文本消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            //如果socket未连接，则退出
            if (socketSend == null || !socketSend.Connected)
            {
                MessageBox.Show("网络连接错误，请重新连入！");
                return;
            }

            try
            {
                var str = txtMsg.Text;
                byte[] buffer = Encoding.UTF8.GetBytes(str);
                socketSend.Send(buffer);
                //发送成功后清空文本框
                txtMsg.Text = string.Empty;
            }
            catch
            {
                MessageBox.Show("网络连接错误，请重新连入！");
            }
        }
        /// <summary>
        /// 不停接受服务器端的消息
        /// </summary>
        private void Receive()
        {
            while (true)
            {
                byte[] buffer = new Byte[1024 * 1024 * 5];
                int r = socketSend.Receive(buffer);

                if (r == 0)
                    break;

                //表示发送文字
                if (buffer[0] == 0)
                {
                    string str = Encoding.UTF8.GetString(buffer, 1, r - 1);
                    ShowMessage(socketSend.RemoteEndPoint + "：" + str);
                }
                //表示发送文件
                else if (buffer[0] == 1)
                {
                    //选择文件保存路径
                    var dialog = new SaveFileDialog();
                    dialog.InitialDirectory = @"D:\BBB";
                    dialog.Title = "请选择保存的文件夹";
                    dialog.Filter = "所有文件|*.*";
                    dialog.ShowDialog(this);

                    var path = dialog.FileName;

                    if (string.IsNullOrEmpty(path))
                    {
                        MessageBox.Show("请先选择保存文件夹！");
                        return;
                    }

                    try
                    {
                        using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            fsWrite.Write(buffer, 1, r - 1);
                        }

                        ShowMessage(socketSend.RemoteEndPoint + "：文件发送成功！");
                    }
                    catch
                    {
                        MessageBox.Show("网络访问错误，请重试！");
                        ShowMessage(socketSend.RemoteEndPoint + "：文件发送失败！");
                    }
                }
                //发送震动
                else if (buffer[0] == 2)
                {
                    //调用震动方法
                    Shake();
                }
                else
                {
                    //其它的发送消息类型
                }
            }
        }
        /// <summary>
        /// 窗体震动ing
        /// </summary>
        private void Shake()
        {
            //原窗体的X坐标
            var x = this.Location.X;
            var y = this.Location.Y;

            //上下移动500次
            for (var i = 0; i < 500; i++)
            {
                this.Location = new Point(x - 20, y - 20);
                this.Location = new Point(x + 20, y + 20);
            }

            //移位完成后，回到原坐标
            this.Location = new Point(x, y);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
    }
}
